pub mod model;

use reqwest::Client;
use serde::{Deserialize, Serialize};
use crate::config::{Auth, get_auth};

#[derive(Serialize, Debug)]
struct RequestBody {
    app_id: String,
    client_secret: String
}

#[derive(Deserialize, Debug)]
struct ResponseBody {
    access_token: String,
    expires_in: String
}

#[derive(Deserialize, Debug)]
struct Gateway {
    url: Option<String>
}

pub async fn get_app_access_token() -> String {
    let Auth {app_id, client_secret}  = get_auth();
    let client = get_client()
        .post("https://bots.qq.com/app/getAppAccessToken")
        .json(&RequestBody { app_id, client_secret })
        .send().await.expect("获取失败！")
        .json::<ResponseBody>().await.expect("转换失败！");
    format!("QQBot {}", client.access_token)
}

pub async fn get_gateway() -> String {
    let token = get_app_access_token().await;
    let gateway = get_client()
        .get("https://api.sgroup.qq.com/gateway")
        .header("Authorization", token)
        .send().await.expect("发送失败！")
        .json::<Gateway>().await.expect("转换JSON失败！");
    match gateway.url {
        None => {
            println!("Gateway的URL为空！");
            String::new()
        }
        Some(url) => {
            url
        }
    }
}

fn get_client() -> Client {
    Client::builder().build().expect("Client构建失败！")
}